import { createRouter, createWebHashHistory } from "vue-router";
import { useUsersStore } from "../store/user";
import axios from "axios";
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      name: "layout",
      component: async () => await import("../components/Layout.vue"),
      children: [
        // 用户管理
        {
          path: "/user",
          name: "User",
          component: async () => await import("../page/User.vue"),
        },
        // 商品管理
        {
          path: "/products",
          name: "Products",
          component: async () => await import("../page/Products.vue"),
        },
        // 订单管理
        {
          path: "/order",
          name: "Order",
          component: async () => await import("../page/Order.vue"),
        },
        {
          path: "/payOk",
          name: "payOk",
          component: async () => await import("../page/PayOk.vue"),
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: async () => await import("../page/Login.vue"),
    },
  ],
});

router.beforeEach((to, from, next) => {
  const store = useUsersStore();
  const { isAuthenticated } = store;
  const noPermissionPaths = ["/login"];
  if (!isAuthenticated && !noPermissionPaths.includes(to.path)) {
    next("/login");
  } else {
    next();
  }
});

export default router;
